package com.coursehub.exercise.repository;

import com.coursehub.exercise.entity.Exercise;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 练习数据访问层接口
 */
@Repository
public interface ExerciseRepository extends JpaRepository<Exercise, String>, JpaSpecificationExecutor<Exercise> {
    
    /**
     * 根据练习名称查找练习
     */
    Optional<Exercise> findByExerciseName(String exerciseName);
    
    /**
     * 根据练习名称模糊查询
     */
    List<Exercise> findByExerciseNameContainingIgnoreCase(String exerciseName);
    
    /**
     * 检查练习名称是否存在
     */
    boolean existsByExerciseName(String exerciseName);
    
    /**
     * 检查练习ID是否存在
     */
    boolean existsByExerciseId(String exerciseId);
    
    /**
     * 根据班级ID查找练习
     */
    List<Exercise> findByClassesId(String classesId);
    
    /**
     * 根据班级ID和练习状态查找练习
     */
    @Query("SELECT e FROM Exercise e WHERE e.classesId = :classesId AND e.exerciseStartTime <= :now AND e.exerciseDeadline >= :now")
    List<Exercise> findActiveExercisesByClassesId(@Param("classesId") String classesId, @Param("now") LocalDateTime now);
    
    /**
     * 根据班级ID查找已结束的练习
     */
    @Query("SELECT e FROM Exercise e WHERE e.classesId = :classesId AND e.exerciseDeadline < :now")
    List<Exercise> findFinishedExercisesByClassesId(@Param("classesId") String classesId, @Param("now") LocalDateTime now);
    
    /**
     * 根据班级ID查找未开始的练习
     */
    @Query("SELECT e FROM Exercise e WHERE e.classesId = :classesId AND e.exerciseStartTime > :now")
    List<Exercise> findUpcomingExercisesByClassesId(@Param("classesId") String classesId, @Param("now") LocalDateTime now);
    
    /**
     * 根据多个条件查询练习
     */
    @Query("SELECT e FROM Exercise e WHERE " +
           "(:exerciseName IS NULL OR LOWER(e.exerciseName) LIKE LOWER(CONCAT('%', :exerciseName, '%'))) AND " +
           "(:classesId IS NULL OR e.classesId = :classesId) AND " +
           "(:isMultipleSubmission IS NULL OR e.isMultipleSubmission = :isMultipleSubmission)")
    List<Exercise> findByMultipleConditions(@Param("exerciseName") String exerciseName,
                                          @Param("classesId") String classesId,
                                          @Param("isMultipleSubmission") Boolean isMultipleSubmission);
    
    /**
     * 根据练习ID列表查询练习
     */
    List<Exercise> findByExerciseIdIn(List<String> exerciseIds);
    
    /**
     * 根据班级ID列表查询练习
     */
    List<Exercise> findByClassesIdIn(List<String> classesIds);
}